package com.financing.platform.web.api;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;



@Controller("AdminSendEmailActionApi")
@RequestMapping("/api/mail")
@Scope("prototype")
public class AdminSendEmailAction extends BaseAction{
	
	@Resource
	private MailSenderService mailSenderService;
	
	@RequestMapping("mailSend.shtml")
	@ResponseBody
	public ResultMap mailSend(HttpServletRequest request,
			HttpServletResponse response) {
		//需要发送地址的总数
		long totalAddressCount = 0L;
		
		//成功发送的总数
		long sendAddressCount = 0L;
		
		//无效地址数
		long badAddressCount = 0L;
		
		//发送失败邮件的总数
		long sendFailAddressCount = 0L;
		
		//无效地址列表
		List<String> badAddresslist = new ArrayList<String>();
		
		//发送失败地址列表
		List<String> sendFailAddressList = new ArrayList<String>();
		
		BufferedReader brEmailAddress = null;
		BufferedReader brEmailContents = null;
		BufferedReader brEmailSubject = null;
		
		try{
			//emailAddress.txt保存所有需要发送邮件的地址.每一行放一个地址."//"为注释本行,不做发送处理
			brEmailAddress = new BufferedReader(new InputStreamReader(new FileInputStream("/disk/emailAddress.txt")));
			
			//emailContentx.txt 保存所需发送邮件的正文,支持html标签
			brEmailContents = new BufferedReader(new InputStreamReader(new FileInputStream("/disk/emailContents.txt")));
			
			//emailSubject.txt 保存所需发送邮件主题 只能一行
			brEmailSubject = new BufferedReader(new InputStreamReader(new FileInputStream("/disk/emailSubject.txt")));
			String sEmailSubject = brEmailSubject.readLine();
			
			StringBuffer sbEmailContents = new StringBuffer();
			String sEmailContentLine = null;
			
			//获取邮件正文内容
			while(null != (sEmailContentLine = brEmailContents.readLine())){
				sbEmailContents.append(sEmailContentLine);
			}
			
			String sEmailAddress = null;
			
			//获取单个地址 如果不是正常的邮件地址则不发送
			while(null != (sEmailAddress = brEmailAddress.readLine())){
				totalAddressCount++;
				if(isEmailAddress(sEmailAddress)){
					MailContentDTO mailContentDto = new MailContentDTO();
					try{
						mailContentDto.setContext(sbEmailContents.toString());
						mailContentDto.setRecAddress(sEmailAddress.trim());
						mailContentDto.setSubject(sEmailSubject);
						mailSenderService.send(mailContentDto);
					}catch(Exception e){
						sendFailAddressCount++;
						sendFailAddressList.add(sEmailAddress+":"+e.getMessage());
						log.error("send email error!",e);
					}
					sendAddressCount++;
				}else{
					badAddressCount++;
					badAddresslist.add(sEmailAddress);
				}
			}
				
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			//关闭邮件地址文件流
			if (null != brEmailAddress ) {
				try {
					brEmailAddress.close();
				} catch (IOException e1) {
				}
			}
			//关闭邮件正文文件流
			if (null != brEmailContents ) {
				try {
					brEmailContents.close();
				} catch (IOException e1) {
				}
			}
			//关闭邮件正文文件流
			if (null != brEmailSubject ) {
				try {
					brEmailSubject.close();
				} catch (IOException e1) {
				}
			}
			log.error("send  error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		resultMap.setAttribute("total", totalAddressCount);
		resultMap.setAttribute("success", sendAddressCount);
		resultMap.setAttribute("fail", sendFailAddressCount);
		resultMap.setAttribute("bad address", badAddressCount);
		resultMap.setAttribute("bad address list:", badAddresslist);
		resultMap.setAttribute("send fail address list :",sendFailAddressCount);
		
		log.info(new StringBuffer().append("send email end! total:").append(totalAddressCount).append("个;success:").append(sendAddressCount)
				.append("个;bad address:").append(badAddressCount).append("个;send fail: ").append(sendFailAddressCount).append("个! good job!"));
		return resultMap;
	}
	
	/**
	 * 判断字符串是否是email地址
	 * @param email
	 * @return
	 */
	private boolean isEmailAddress(String email){
		
		if(null == email || email.trim().length() <= 0 || email.trim().startsWith("//")){
			return false;
		}else{
			Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			return m.matches();
		}
	}
	
}
